# Create your views here.
from django.shortcuts import render_to_response
from Usuarios.models import Usuario
from django.views.decorators.csrf import csrf_exempt
import MySQLdb
from MySQLdb import cursors
import string



def registrar(request):
	return render_to_response('registrarUsuario.html')


@csrf_exempt	
def registrar2(request):
		
	#db=MySQLdb.connect(host="localhost",user="root",passwd="root",db="umbook")
	
	
	#cursor=db.cursor()
	

	username=request.POST["username"]
	first_name=request.POST["first_name"]
	last_name=request.POST["last_name"]
	mail=request.POST["mail"]
	password=request.POST["password"]
	sexo=request.POST["sexo"]
	dia=request.POST["dia"]
	mes=request.POST["mes"]
	anio=request.POST["anio"]

	birthday= dia + "/" + mes + "/" + anio

	
	#rows=cursor.execute("SELECT * FROM Usuarios_usuario WHERE username=%s",username)
	#db.commit()	
#	user=cursor.fetchall()
	
	try:

		registro=Usuario.objects.get(username=username)
		
		return render_to_response('registrarUsuario.html',{'first_name':first_name,'last_name':last_name,'mail':mail,'dia':dia,'mes':mes,'anio':anio,'mensaje':"Usuario incorrecto",'s':1,'sexo1':sexo,'sexo2':string.upper(sexo)})
		
		
	except:
		u=Usuario(username=username,first_name=first_name,last_name=last_name,mail=mail,password=password,sexo=sexo,birthday=birthday,estado=1)
		u.save()
		return render_to_response('registrarUsuario2.html')	
		

@csrf_exempt
def umbook(request):
	
	#seguridad: pag 144 libro django
	#db=MySQLdb.connect(host="localhost",user="root",passwd="root",db="umbook")
	#cursor=db.cursor()

	username=request.POST["username"]
	password=request.POST["password"]
	
	#rows=cursor.execute("SELECT * FROM Usuarios_usuario WHERE username='" + username + "' && password='" + password + "'")
	#db.commit()	

	
	
	try:

		registro=Usuario.objects.get(username=username,password=password)
		#cant=Usuario.objects.all().filter(username=username,password=password).count()
		
		request.session["id"] = registro.id
		request.session["username"] = registro.username
		request.session["log"] = 1
		
		return render_to_response('paginaInicial.html',{'id':registro.id})
				
	except:
#		if cant <= 0:
		return render_to_response('registrarUsuario.html',{'mensaje2':"Usuario Incorrecto"})	
		
		
		
@csrf_exempt
def prueba(request):		
	if request.session["log"] != 1:
		return render_to_response('registrarUsuario.html')
		
	else:
		return render_to_response('prueba.html')
		

@csrf_exempt		
def cerrarSesion(request):
	request.session["log"] = 0
	return render_to_response('registrarUsuario.html')
		
		
		
		
